package com.example.projects;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;


public class History extends Fragment {

	
	ScrollView scroll;
	LinearLayout ll;
	
	public static Fragment newInstance(Context context) {
		History f = new History();	
		
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		View root = (ViewGroup) inflater.inflate(R.layout.history_list, null);		
		scroll = (ScrollView) root.findViewById(R.id.scrollhis);
		ll = (LinearLayout)root.findViewById(R.id.linearhis);
		drawScreen(container);
		
		return root;
	}
	
	private void drawScreen(ViewGroup container){
		
        ll.removeAllViews();
        scroll.removeAllViews();
        
		ArrayList<String> Itemlist = new ArrayList<String>();
	    XmlPullParserFactory factory;
		try {
			factory = XmlPullParserFactory.newInstance();
			factory.setValidating(false);
	        XmlPullParser xpp = factory.newPullParser();
	        
	        File f = new File(container.getContext().getFilesDir().getAbsolutePath()+"/hist.xml");
	        if(f.exists()) {
		        //InputStream raw = getActivity().getApplicationContext().getAssets().open("/data/data/com.example.projects/files/fav.xml");
		        FileInputStream fis = new FileInputStream(f);
		        xpp.setInput(fis, "UTF-8");
		        int eventType = xpp.getEventType();
		        while (eventType != XmlPullParser.END_DOCUMENT) {
		        	System.out.println("1");
			        if(eventType == XmlPullParser.START_DOCUMENT) {
			        	System.out.println("start document");	        
			        } else if(eventType == XmlPullParser.START_TAG) {
			            //Itemlist.add(xpp.getName());
			            System.out.println("1");
			        } else if(eventType == XmlPullParser.END_TAG) {
			            //Itemlist.add(xpp.getName());
			            System.out.println("2");
			        } else if(eventType == XmlPullParser.TEXT) {
			            Itemlist.add(xpp.getText());
			        }
		        	eventType = xpp.next();
		        }
	        }
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
        
        
        for(int i = 0; i < Itemlist.size(); i++){
    		String str = "";
    		String namestr = "";
        	try {
        		System.out.println("HistContext:"+container.getContext().getFilesDir().getAbsolutePath());
				str = readFile(Itemlist.get(i), container.getContext().getFilesDir().getAbsolutePath());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
        	try {
        		JSONObject json_data = new JSONObject(str);
        		namestr = json_data.getString("Name");

			} catch (JSONException e) {
				e.printStackTrace();
			}
        	
        	Button b = new Button(container.getContext());
        	b.setText(namestr);
        	b.setTag(Itemlist.get(i));
        	b.setOnClickListener(new OnClickListener() {
        		  public void onClick(View v) 
        		  {
        			  	Intent intent = new Intent();
        			  	intent.setClassName("com.example.projects", "com.example.projects.Information");
        			  	String barcode = v.getTag().toString();
						//direct the barcode to comment class
						intent.putExtra(Main.BARCODE, barcode);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
        		  }
        	});
        	b.setBackgroundResource(R.drawable.list_button);
        	b.setWidth(ll.getMeasuredWidth());
        	ll.addView(b);
        	
        }

        scroll.addView(ll);
	}
	
	private String readFile(String barcode, String path) throws FileNotFoundException, IOException {
		FileInputStream stream = new FileInputStream(new File(path+"/" + barcode + "product.json"));
		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		String str = Charset.defaultCharset().decode(bb).toString();
		stream.close();
		return str;
	}
	
}
